package com.cloudinnov.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import com.alibaba.fastjson.JSON;
import com.cloudinnov.model.FireCRTEvent;

/**
 * @version 1.5
 * @remark 维持与火灾控制器的TCP长连接
 */
public class FireAlarmConnect extends Thread {
	private static final String CODEDFORMAT = "gb2312";
	private static final int REVEIVEBUFFERSIZE = 1024 * 8;// 接收缓存8k
	private Socket socket;
	private boolean run = true;

	public FireAlarmConnect(Socket socket) {
		this.socket = socket;
	}
	
	@Override
	public void run() {
		connectReceive();
	}
	
	public void connectReceive() {
		InputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader bufferedReader = null;
		try {
			inputStream = (InputStream) socket.getInputStream();// 获取一个输入流，接收服务端的信息
			inputStreamReader = new InputStreamReader(inputStream, CODEDFORMAT);// 包装成字符流，提高效率,gbk
			bufferedReader = new BufferedReader(inputStreamReader);// 缓冲区
			char[] rcchar = new char[REVEIVEBUFFERSIZE];
			// TCP长连接，十秒一个心跳数据包，连接断开会抛出异常退出接收线程
			while (run) {// 长连接读取CRT信息，连接断开会抛出异常
				int len = bufferedReader.read(rcchar);// 堵塞读取
				if (len == -1) {
					throw new Exception("socket连接出错");
				}
				String crtstrs = String.valueOf(rcchar, 0, len);
				String[] arr = crtstrs.split("活");
				for (String s : arr) {
					if (s.length() != 0) {
						String[] crtStrArr = s.split("\n结束");
						for (String acrtevent : crtStrArr) {
							FireCRTEvent fireCRTEvent = StringUtil.StrToFireCRTEvent(acrtevent);
							if (fireCRTEvent != null) {
								FireAlarmServer.fireTemplate.convertAndSend(JSON.toJSONString(fireCRTEvent));
							}
						}
					}
				}
			}
		} catch (Exception e) {
			// 与火灾系统连接中断
			// System.err.println("connect lost");
			try {
				bufferedReader.close();
				inputStreamReader.close();
				inputStream.close();
				socket.close();
			} catch (IOException e1) {
			}
		}
	}
}

class StringUtil {
	private static final String timeformatOFWIndowsXP = "y-M-d a hh:mm:ss";//// 处理火灾系统时间格式
	private static final String timeformatOFWindows10 = "y/M/d H:mm:ss";

	// 格式化CRT火灾系统时间到本地系统格式
	static private Long getLongByViewDate(String viewdate) {
		SimpleDateFormat df = new SimpleDateFormat(timeformatOFWIndowsXP);// 设置日期格式
		try {
			return df.parse(viewdate).getTime();
		} catch (ParseException e) {
			// 时间解析失败
		}
		df = new SimpleDateFormat(timeformatOFWindows10);// 设置日期格式
		try {
			return df.parse(viewdate).getTime();
		} catch (ParseException e) {
			
		}
		return null;
	}
	
	public static FireCRTEvent StrToFireCRTEvent(String recinf) {
		FireCRTEvent fireCRTEvent = new FireCRTEvent();
		Calendar a = Calendar.getInstance();
		int aindextimestart = recinf.lastIndexOf(String.valueOf(a.get(Calendar.YEAR)));
		String strViewTime = recinf.substring(aindextimestart, recinf.length());// 有用数据包会以时间为结尾
		fireCRTEvent.setOccurrenceTime(getLongByViewDate(strViewTime));
		String strinf = recinf.substring(0, aindextimestart).trim();
		String infs[] = strinf.split(" ");
		String info = infs[0];
		if (infs.length == 2) {// 与系统连接恢复时,特殊处理数据包eq: 系统故障恢复: 远程传输恢复
			fireCRTEvent.setEvent(infs[0]);
			fireCRTEvent.setDevice(infs[1]);
			return fireCRTEvent;
		}
		fireCRTEvent.setEvent(infs[0]);
		fireCRTEvent.setPosition(infs[1]);
		fireCRTEvent.setDevice(infs[2]);
		if (!info.equals("其他事件:") && !info.equals("故障:") && !info.equals("故障恢复:")) {
			if (!infs[infs.length - 1].equals("层")) {// 消息包含附加地理位置信息
				String[] values = infs[infs.length - 1].split("号");
				fireCRTEvent.setDeviceId(values[1]);
			}
		} else {
			fireCRTEvent = null;
		}
		return fireCRTEvent;
	}
	
	public static void main(String[] args) {
		String[] crtstr = { "模拟火警: 0号机1回路3号地址 输入模块 火警 层 2017EQAF2HL2017-5-2 下午 03:58:40",
				"模拟火警: 0号机1回路3号地址 输入模块 火警 层 2017-5-2 下午 03:58:40",
				"模拟火警: 0号机1回路3号地址 输入模块 火警 层 EQAF2HL2017/5/2 15:58:40", "模拟火警: 0号机1回路3号地址 输入模块 火警 层 2017/5/2 15:58:40",
				"系统故障恢复: 远程传输恢复2017-5-1 下午 11:35:47", "系统故障恢复: 远程传输恢复2017/5/2 21:53:37",
				"模拟反馈: 0号机1回路1号地址 智能输入  层 K20+6582017-5-1 下午 11:35:47" };
		for (String s : crtstr) {
			FireCRTEvent fireCRTEvent = StringUtil.StrToFireCRTEvent(s);
			System.err.println(JSON.toJSONString(fireCRTEvent));
		}
	}
}
